package cn.intotw.pp.client.core;

import cn.intotw.pp.entity.PPProtocolFrame;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.ReferenceCountUtil;

/**
 * @author Chenxiang
 * @Description:
 * @create 2018/8/21 14:53
 */
public class PPClientHandler extends ChannelInboundHandlerAdapter {
    // 客户端与服务端，连接成功的售后
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        // 发送SmartCar协议的消息
        // 要发送的信息
        String data = "P10001"+"&|"+"123456"+"&|"+"654213"+"^|"+"q654213q"+"*|"+"123456";
        // 获得要发送信息的字节数组
        byte[] content = data.getBytes();
        // 要发送信息的长度
        int contentLength = content.length;

        PPProtocolFrame ppProtocolFrame=new PPProtocolFrame();
        ppProtocolFrame.setContentLength(contentLength);
        ppProtocolFrame.setContent(content);
        for (int i = 0; i < 2; i++) {
            ctx.write(ppProtocolFrame);
        }
        ctx.writeAndFlush(ppProtocolFrame);
    }
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg)
            throws Exception {
        try {
            // 用于获取客户端发来的数据信息
            PPProtocolFrame body = (PPProtocolFrame) msg;
            System.out.println("Client接受的客户端的信息 :" + body.toString());

        } finally {
            ReferenceCountUtil.release(msg);
        }
    }



    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
            throws Exception {
        ctx.close();
    }

}